package sqlengine.queryExecution;

import java.util.Map;
import java.util.Vector;

import sqlengine.database.DataFile;
import sqlengine.database.DataManager;
import sqlengine.database.Index;

public class Basicexecution {

	public DataFile createTable(String fileName, String key,
		Map<String, Integer> descriptor, Vector<String> order) {		
		DataFile df=null;
		try{			
			df = DataManager.createFile(fileName, descriptor, order);
		    df.setPrimaryKey(key);
			
			df.createIndex(fileName + "," + key, key);
		}catch(IllegalArgumentException e){
			System.out.println("file/index name already exist!");
			throw new IllegalArgumentException(e);
		}
		return df;
	}

	public void dropTable(String fileName) {
		
		Map<String, DataFile> files = DataManager.getOpenedFiles();
		if(files.containsKey(fileName)){
			DataFile df = files.get(fileName);
			df.dropFile();
		}else{
			throw new IllegalArgumentException("file does not exist!");
		}		
	}

	public Index executeCreateIndex(String fileName, String indexName,
			String column) {
		Index index =null;
		try{				
			Map<String, DataFile> files = DataManager.getOpenedFiles();
			if(!(files.containsKey(fileName))){
				throw new IllegalArgumentException("table does not exist!");
			}
			DataFile df = files.get(fileName);
			index= df.createIndex(indexName, column);
		}catch(IllegalArgumentException e){
			System.out.println("executing create index error!");
			throw new IllegalArgumentException(e);
		}
		return index;
	}

	public void executeDropIndex(String fileName, String indexName) throws Exception {
		Map<String, DataFile> files = DataManager.getOpenedFiles();
		if(!(files.containsKey(fileName))){throw new IllegalArgumentException("table does not exist!"); }
		DataFile df = files.get(fileName);
		try {
			df.dropIndex(indexName);
		} catch (Exception e) {
			throw new IllegalArgumentException("index not exist");
		}
	}

	public int executeInsert(String fileName, Map<String, String> record) {
		
		Map<String, DataFile> files = DataManager.getOpenedFiles();
		DataFile df = files.get(fileName);
	
		String Pkey=df.getPrimaryKey();
		if(!record.containsKey(Pkey)){
			throw new IllegalArgumentException("Key is null");
		}		
		String Pvalue= record.get(Pkey);
		Index index=df.getIndices().get(fileName + "," + Pkey);
		if(index.existKey(Pvalue)){
			throw new IllegalArgumentException("duplicate key value!");
		}
		int count = df.insertRecord(record);
		return count;
	}

}
